<?php
//地理位置
if(!defined('__ROOT__')) die ("Access Denied.");
class Wx_Location{
    /**
     * 相关参数
     *
     * @access private
     */
    private $_params = array();
    /**
     * 析构函数
     *
     * @access public
     */
    public function __construct($params) {
        $this->_params = $params;
    }
    /**
     * 执行操作
     *
     * @access public
     */
    public function execute(){
        $func = '_'.$this->_params['func'];
        if(method_exists(__CLASS__ ,$func)){
            return $this->{$func}();
        }
        return false;
    }
    /**
     * 按坐标查找商户
     *
     * @access private
     */
    private function _businesses(){
        //点评网API
        $api = 'http://api.dianping.com/v1/business/find_businesses_by_coordinate';
        $appKey = 'xxx';
        $appSecret = 'xxx';
        $params = array(
            'latitude'=>$this->_params['x'],
            'longitude'=>$this->_params['y'],
            'radius'=>'1000',
            'sort'=>'1',
            'limit'=>8,
            'platform'=>2, //2:HTML5站链接（适用于移动应用和联网车载应用）
            'format'=>'json'
        );
        //按照参数名排序
        ksort($params);
        //连接待加密的字符串
        $codes = '';
        //请求的URL参数
        $queryString = '';
        while (list($key, $val) = each($params)){
            $codes .=($key.$val);
            $queryString .=('&'.$key.'='.urlencode($val));
        }
        $codes = $appKey.$codes.$appSecret;
        $sign = strtoupper(sha1($codes));
        $httpUrl = $api.'?appkey='.$appKey.'&sign='.$sign.$queryString;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $httpUrl);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
        $data = json_decode(curl_exec($curl), true);
        curl_close($curl);
        unset($api,$appKey,$appSecret,$params,$queryString,$codes,$sign,$curl);
        $status = $data['status'];
        $result = array('counts'=>0,'xml'=>'');
        if('OK'==$status){
            $result['counts'] = $data['count'];
            $output = '';
            if($data['count']>0){
                $tpl = data::get('config.tpl.item');
                foreach($data['businesses'] as $row){
                    $output .= sprintf($tpl ,$row['name'].$row['branch_name'],$row['address'],$row['s_photo_url'],$row['business_url']);
                }
            }
            $result['xml'] = $output;
        }
        unset($output ,$data,$status);
        return $result;
    }
}